package org.herui.campus.common.utils;

import cn.hutool.core.util.ReflectUtil;
import com.mlnx.common.utils.MyLog;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SmartReflectUtil {

    static MyLog log = MyLog.getLog(SmartReflectUtil.class);

    public static void invokeSet(String name, Object obj, Object... args){
        String methodName = "set" + getMethodName(name);

        Field field = ReflectUtil.getField(obj.getClass(), name);
        if (field == null){
            log.error("{} 变量 {} 不存在", obj.getClass(), name);
            return;
        }
        Class<?> type = field.getType();
        if (type.equals(Integer.class) ){
            args[0] = Integer.valueOf(args[0].toString());
        }else if (type.equals(int.class)){
            args[0] = Integer.valueOf(args[0].toString()).intValue();
        }else if (type.equals(Long.class)){
            args[0] = Long.valueOf(args[0].toString());
        }else if (type.equals(long.class)){
            args[0] = Long.valueOf(args[0].toString()).longValue();
        }else if (type.equals(Float.class)){
            args[0] = Float.valueOf(args[0].toString());
        }else if (type.equals(float.class)){
            args[0] = Float.valueOf(args[0].toString()).floatValue();
        }

        Method method = ReflectUtil.getMethodOfObj(obj, methodName, args);

        try {
            method.invoke(obj, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object invokeGet(String name, Object obj, Object... args){
        String methodName = "get" + getMethodName(name);
        Method method = ReflectUtil.getMethodOfObj(obj, methodName, args);
        if (method == null){
            methodName = "is" + getMethodName(name);
            method = ReflectUtil.getMethodOfObj(obj, methodName, args);
        }

        if (method == null){
            log.error("{} 方法 {} 不存在", obj.getClass(), methodName);
            return null;
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 首字母大写(进行字母的ascii编码前移，效率是最高的)
     *
     * @param fieldName 需要转化的字符串
     */
    private static String getMethodName(String fieldName) {
        char[] chars = fieldName.toCharArray();
        chars[0] = toUpperCase(chars[0]);
        return String.valueOf(chars);
    }


    /**
     * 字符转成大写
     *
     * @param c 需要转化的字符
     */
    private static char toUpperCase(char c) {
        if (97 <= c && c <= 122) {
            c ^= 32;
        }
        return c;
    }
}
